package com.shenganyuan.smac.msg;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.oklib.utils.assist.DateUtil;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.widget.recyclerview.CoreRecyclerView;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.beans.ApiMessage;
import com.shenganyuan.smac.common.beans.BaseBoolResult;
import com.shenganyuan.smac.common.beans.Msg;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.msg.adapter.AdapterChat;
import com.shenganyuan.smac.msg.model.BeanChatTo;
import com.shenganyuan.smac.msg.model.ChatMessage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 聊天界面
 *
 * @author Damon.Han
 */
public class ActMsgChat extends BaseActivity {
    @BindView(R.id.common_toolbar_center_title)
    TextView commonToolbarCenterTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recycler)
    CoreRecyclerView recycler;
    @BindView(R.id.et_send)
    EditText etSend;
    @BindView(R.id.btn_send)
    Button btnSend;

    private BeanChatTo beanChatTo;
    private AdapterChat mAdapter;
    List<ChatMessage> chatMessages = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.act_msg_chat;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
    }


    @Override
    public void initData() {
        beanChatTo = (BeanChatTo) getIntent().getSerializableExtra("beanChatTo");
        if (beanChatTo == null) {
            finish();
        }
        mAdapter = new AdapterChat(chatMessages);
        recycler.init(mAdapter);
        setTitle(beanChatTo.name);
        getDataFromServer();
    }

    /**
     *
     */
    private void getDataFromServer() {
        String jsuserid = App.getCurrentUser().getId();
        ViseHttp.RETROFIT().create(Api.class).getDhMsgs(jsuserid, beanChatTo.id, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(new ApiCallbackSubscriber(new ACallback<ApiMessage>() {
                    @Override
                    public void onSuccess(ApiMessage apiRisk) {
                        try {
                            List<Msg> messages = apiRisk.getMessage();
                            if (messages != null && messages.size() > 0) {
                                chatMessages.clear();
                                ChatMessage chatMessage = null;
                                String userId = App.getCurrentUser().getId();
                                for (int i = messages.size() - 1; i >= 0; i--) {
                                    Msg m = messages.get(i);
                                    String content = m.getNr();
                                    String fbUserId = m.getFbUserid();
                                    String fbName = m.getFbname();
                                    String jsUserId = m.getJsUserid();
                                    String jsName = m.getJsname();
                                    String fbTime = m.getFbTime();
                                    String sender = "";
                                    sender = fbName;
                                    ChatMessage.Type type = null;
                                    if (userId.equalsIgnoreCase(fbUserId)) {
                                        type = ChatMessage.Type.SENT;
                                    } else {
                                        type = ChatMessage.Type.RECEIVED;
                                    }
                                    Date date = DateUtil.getDateByFormat(fbTime, new SimpleDateFormat("yyyyMMddhhmmss"));
                                    chatMessage = new ChatMessage(content, date.getTime(), type, sender);
                                    chatMessages.add(chatMessage);
                                }
                                mAdapter.notifyDataSetChanged();
                                recycler.getRecyclerView().smoothScrollToPosition(mAdapter.getItemCount() - 1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        SnackbarUtil.showShort(getWindow().getDecorView(), "获取消息失败");
                    }
                }));
    }

    @OnClick(R.id.btn_send)
    public void onViewClicked() {
        saveMsgToServer();
    }

    /**
     * 发送消息
     */
    private void saveMsgToServer() {
        String fbuserid = App.getCurrentUser().getId();
        String str = etSend.getText().toString().trim();
        if (TextUtils.isEmpty(str)) {
            SnackbarUtil.showShort(getWindow().getDecorView(), "内容不能为空");
            return;
        }
        Map<String, String> req = new HashMap<>();
        req.put("fbuserid", fbuserid);
        req.put("jsuserid", beanChatTo.id);
        req.put("token", App.getAccessToken());
        req.put("nr", str);
        ViseHttp.RETROFIT().create(Api.class).messagesave(req)
                .compose(RxUtil.rxSchedulerHelper())
                .subscribe(new ApiCallbackSubscriber<BaseBoolResult>(new ACallback<BaseBoolResult>() {
                    @Override
                    public void onSuccess(BaseBoolResult data) {
                        try {
                            if ("true".equalsIgnoreCase(data.getResult())) {
                                ChatMessage chatMessage = new ChatMessage(str, System.currentTimeMillis(), ChatMessage.Type.SENT, "我");
                                mAdapter.addData(chatMessage);
                                recycler.getRecyclerView().smoothScrollToPosition(mAdapter.getData().size() - 1);
                                etSend.setText("");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        SnackbarUtil.showShort(getWindow().getDecorView(), "获取消息失败");
                    }
                }));
    }
}
